const { defineConfig } = require("cypress");
// const cucumber = require('cypress-cucumber-preprocessor').default
const { addCucumberPreprocessorPlugin } = require("@badeball/cypress-cucumber-preprocessor");
const createBundler = require("@bahmutov/cypress-esbuild-preprocessor");
const { createEsbuildPlugin } = require("@badeball/cypress-cucumber-preprocessor/esbuild");
const allureWriter = require('@shelex/cypress-allure-plugin/writer');
const fs = require('fs');
const csv = require('csv-parser');
const config = require('./config');


module.exports = defineConfig({
  projectId: "aaqdxz",
  viewportWidth: 1920,
  viewportHeight: 1080,
  reporter: "mochawesome",

  reporterOptions: {
    reportFilename: "[status]-[name]-report",
    reportDir: "cypress/results",
    reportTitle: "Cypress-E2E",
    reportPageTitle: "Cypress-E2E-Report",
    overwrite: false,
    html: true,
    json: true,
  },

  video: true,
  defaultCommandTimeout: 10000,
  // 可替换的配置, config中
  db: config.db,
  e2e: {
    baseUrl: config.baseUrl,
    env: {
      // environment: ["care_old", "vghks2", "jianshun2", "local", "prod", "pch", "stipendiary", "elderly_dev", "vghtc", "weigong", "yaoi", "yenpapa", "stipendiary_puli"]
      environment: config.environment,
      // wisleepUrl: config.baseUrl
    },
    // 打开e2estudio,  可以录测试脚本
    experimentalStudio: true,


    setupNodeEvents(on, config) {
      //db operation
      on("task", {
        dbQuery: (query) => require("cypress-postgres")(query.query, query.connection)
      });

      //log
      on('task', {
        log(message) {
          console.log(message);
          return null;
        },
      });

      //parse csv data
      on('task', {
        parsecsv(csvfile) {
          return new Promise((resolve) => {
            const results = [];
            fs.createReadStream(csvfile)
              .pipe(csv())
              .on('data', (data) => results.push(data))
              .on('end', () => {
                console.log(results);
                return resolve(results);
              });
          });
        },
      });

      //read file
      on('task', {
        readFileMaybe(filename) {
          var result = "";
          if (fs.existsSync(filename)) {
            result = fs.readFileSync(filename, 'utf8');
            console.log(result);
            return result;
          }
          console.log(result);
          return null;
        },
      });

      // import cucmber plugin
      addCucumberPreprocessorPlugin(on, config);
      on("file:preprocessor", createBundler({ plugins: [createEsbuildPlugin(config)] }));

      //allure report dashboard
      allureWriter(on, config);


      return config;
    },

    specPattern: ["cypress/**/**/*.{spec,cy}.{js,jsx,ts,tsx}"],
  },
});
